// pages/driver/trainDetail/signingMap.js
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    longitudewx: '',//经度
    latitudewx: '',//纬度
    windowHeight: '',//屏幕高度
    windowWidth: '',//屏幕宽度
    radius: '',//签到半径
    signStatus: '',//签到状态
    signoutStatus: '',//签离状态
    mIDD: '',//会议IDD
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var longitude = options.longitude
    var latitude = options.latitude
    
    var that = this
    that.setData({
      radius: options.radius, //签到半径
      signStatus: options.QDZT,
      signoutStatus: options.QLZT,
      mIDD: options.mIDD
    })
    // 获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 可使用窗口宽度、高度
        console.log('height=' + res.windowHeight)
        console.log('width=' + res.windowWidth)
        // 计算主体部分高度,单位为px
        that.data.windowHeight = res.windowHeight
        that.data.windowWidth = res.windowWidth
        reversQQlocate(longitude, latitude, that.data.radius, that)
        // zhuanZB(longitude, latitude)
      }
    })




  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //点击签到事件
  controltap(e) {
    // console.log(e.controlId)
    // var userType = wx.getStorageSync('userType');
    // if (userType == 1 || userType == 2) {
    //   console.log('车公司，旅行社不获取位置')
    //   return
    // }
    //计算两点间距离
    var that = this
    // wx.getLocation({
    //   type: 'wgs84',
    //   success: function (res) {
    //     console.log('腾讯经纬度')
    //     console.log(res.longitude, res.latitude)
    //     that.calculate(res.longitude, res.latitude)
    //   }, fail(res) {
    //     console.log(res)
    //   }
    // })
    that.calculate()


  },
  //计算两点间距离方法
  calculate: function () {
    var that = this

    // var DEF_PI = 3.14159265359; // PI
    // var DEF_2PI = 6.28318530712; // 2*PI
    // var DEF_PI180 = 0.01745329252; // PI/180.0
    // var DEF_R = 6370693.5; // radius of earth
    // var dx, dy, dew;
    // var distance;
    // // 角度转换为弧度
    // console.log(longitudeLocation, latitudeLocation, that.data.longitudewx, that.data.latitudewx)
    // var ew1 = longitudeLocation * DEF_PI180;
    // var ns1 = latitudeLocation * DEF_PI180;
    // var ew2 = that.data.longitudewx * DEF_PI180;
    // var ns2 = that.data.latitudewx * DEF_PI180;
    // // 经度差
    // dew = ew1 - ew2;
    // // 若跨东经和西经180 度，进行调整
    // if (dew > DEF_PI)
    //   dew = DEF_2PI - dew;
    // else if (dew < -DEF_PI)
    //   dew = DEF_2PI + dew;
    // dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
    // dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)

    // // 勾股定理求斜边长
    // distance = Math.sqrt(dx * dx + dy * dy).toFixed(0);
    // console.log('###')
    // console.log(distance)

    /*****************/

    // var radLat1 = latitudeLocation * Math.PI / 180.0;
    // var radLat2 = that.data.latitudewx * Math.PI / 180.0;
    // var a = radLat1 - radLat2;
    // var b = longitudeLocation * Math.PI / 180.0 - that.data.longitudewx * Math.PI / 180.0;
    // var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    // s = s * 6378.137;
    // s = Math.round(s * 10000) / 10000;
    // console.log(s);

    /******************/

    var MapApi = new QQMapWX({
      key: 'ORIBZ-4SMCD-UQQ4D-HCT67-FBNLK-3FBMO'
    })

    console.log(that.data.longitudewx, that.data.latitudewx)
    MapApi.calculateDistance({
      mode: 'walking',
      to: [{
        latitude: that.data.latitudewx,
        longitude: that.data.longitudewx
      }],

      success: function (res) {
        console.log(res);
        var distance = res.result.elements[0].distance
        console.log(distance)
        distance = distance - 50
        //如果距离小于签到半径，则签到成功
        if (distance < that.data.radius) {
          // wx.showToast({
          //   title: '签到成功',
          //   icon: 'none',
          // })
          var lat = res.result.elements[0].from.lat
          var lng = res.result.elements[0].from.lng
          // ****先根据from坐标获取address位置说明 ， 然后调用调用接口签到
          that.getAddress(lat, lng)



        } else {
          //大于签到半径，提示不在范围内
          wx.showToast({
            title: '您不在签到范围之内',
            icon: 'none',
          })
        }
      },
      fail: function (res) {
        var title = ''
        //未开启定位服务
        if (res.status == 1000) {
          title = '定位服务尚未开启'
        }
        else if (res.status == 373) {
          title = '您距离会议地点过远'
        }
        else {
          title = '定位服务尚未开启'
        }


        //两点间距离超过10km，腾讯地图api会返回错误信息
        wx.showToast({
          title: title,
          icon: 'none',
        })

        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    })

  },

  //根据from坐标获取address位置说明
  getAddress: function (lat, lng) {
    var that = this
    var MapApi = new QQMapWX({
      key: 'ORIBZ-4SMCD-UQQ4D-HCT67-FBNLK-3FBMO' // 必填
    });
    MapApi.reverseGeocoder({
      location: {
        latitude: lat,
        longitude: lng
      },
      success: function (res) {
        console.log(res);
        console.log(res.result.address)
        var address = res.result.address


        var ashx = ''
        var signMsg = ''
        if (that.data.signStatus == 1) {
          //签离
          ashx = 'Meeting/LeaveSign.ashx'
          signMsg = '签离成功'
        } else {
          //签到
          ashx = 'Meeting/DriverSign.ashx'
          signMsg = '签到成功'
        }
        //调用签到接口
        that.doSign(ashx, address, lat, lng, signMsg)



      },
      fail: function (res) {

        wx.showToast({
          title: '网络错误',
          icon: 'none',
        })
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },

  //调用签到或者签离接口
  doSign: function (ashx, address, lat, lng, signMsg) {
    var that = this
    var userInfo = wx.getStorageSync('userInfo')
    var userType = wx.getStorageSync('userType')
    var tel = userInfo.sTel
    console.log(ashx)
    wx.request({
      url: 'https://www.lanshuicar.com/Server/' + ashx,
      data: {
        type: userType,
        id: userInfo.Id,
        address: address,
        long: lng,
        lat: lat,
        mIDD: that.data.mIDD,
        deviceNum: tel
      },
      method: 'GET',
      success: function (res) {
        // success
        console.log(res)
        var code = res.data.code;
        if (code == 0) {
          // backpage.setData({
          //   backtag: 1,
          // });
          setTimeout(function () {
            wx.showToast({
              title: signMsg,
            })
          }, 1000)
          wx.navigateBack({
          })

          var pages = getCurrentPages()
          var backpage = pages[pages.length - 2]
          backpage.getmeetingdetail()

          var backpage3 = pages[pages.length - 3]
          backpage3.setData({
            backtag: 1,
          });


          // if(signMsg == 'signout'){
          //   backpage.signMsg = 2    //2代表签离标记
          // }else{
          //   backpage.signMsg = 1     //1代表签到标记
          // }



        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      },
      fail: function (res) {
        console.log(res)
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
        })
        // fail
      }
    })
  },







})

// function zhuanZB(longitudebaidu, latitudebaidu) {
//   wx.showToast({
//     title: '正在加载...',
//     icon: 'loading',
//     duration: 10000
//   });

//   wx.request({
//     url: 'http://apis.map.qq.com/ws/coord/v1/translate?locations=' + latitudebaidu + ',' + longitudebaidu + '&type=3&key=ORIBZ-4SMCD-UQQ4D-HCT67-FBNLK-3FBMO',
//     // locations:latitudebaidu,longitudebaidu,
//     // type:3,
//     // key:'ORIBZ-4SMCD-UQQ4D-HCT67-FBNLK-3FBMO',
//     method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
//     // header: {}, // 设置请求的 header
//     success: function (res) {
//       wx.hideToast();
//       // success
//       // var data = tool.getRegularJson(res.data);
//       console.log(res);

//     },
//     fail: function (res) {
//       console.log(res)
//     },
//     complete: function () {
//       // complete
//       wx.stopPullDownRefresh();
//     }
//   })
// }


function reversQQlocate(longitudebaidu, latitudebaidu, radius, that) {
  var demo = new QQMapWX({
    key: 'ORIBZ-4SMCD-UQQ4D-HCT67-FBNLK-3FBMO'
  });
  console.log(longitudebaidu, latitudebaidu)
  demo.reverseGeocoder({
    location: {
      longitude: longitudebaidu,
      latitude: latitudebaidu,
    },
    coord_type: 3,//baidu经纬度

    success: function (res) {
      var location = res.result.ad_info.location;
      console.log(location.lat, location.lng)
      that.setData({
        latitudewx: location.lat,
        longitudewx: location.lng,
        markers: [{
          // iconPath: "../../../images/order_list/locate.png",
          id: 0,
          latitude: location.lat,
          longitude: location.lng,
          width: 15,
          height: 15,
          // callout: {
          //   content: '####32',
          //   color: '#fff',
          //   fontSize: 17,
          //   bgColor: '#7abcf6',
          //   display: 'ALWAYS',
          //   borderRadius: 8,
          //   padding: 5,

          // },

        }],
        circles: [{
          latitude: location.lat,
          longitude: location.lng,
          radius: radius,
          fillColor: '#7cb5ec88',
          color: '#7cb5ec88'

        }],


      })

      // signStatus: options.QDZT,
      // signoutStatus: options.QLZT
      //如果未签到 就显示签到按钮
      console.log(that.data.signStatus, that.data.signoutStatus)
      if (that.data.signStatus == 0 && that.data.signoutStatus == 0) {
        that.setData({
          controls: [{
            id: 2,
            position: {
              left: that.data.windowWidth / 2 - 54,
              top: that.data.windowHeight - 100,
              width: 108,
              height:43
            },
            iconPath: '../../../images/sign.png',
            clickable: true
          }],
        })
      }
      //如果签到了还未签离就显示 签离按钮
      else if (that.data.signStatus == 1 && that.data.signoutStatus == 0) {
        that.setData({
          controls: [{
            id: 2,
            position: {
              left: that.data.windowWidth / 2 - 65,
              top: that.data.windowHeight - 100,
              width: 130,
              height: 45
            },
            iconPath: '../../../images/signout.png',
            clickable: true
          }],
        })
      }
      //完成了 隐藏按钮
      else if (that.data.signStatus == 1 && that.data.signoutStatus == 1) {
        that.setData({
          controls: [{}],
        })
      }




    },
    fail: function (res) {
      console.log(res);
      wx.showToast({
        title: '请检查定位服务',
        icon: 'none'
      })
      // that.showError('未获取到目标位置,请重新进行定位')
    },
    complete: function (res) {
      console.log(res);
    }
  });

}

